package com.bootdo.app.controller.wechat;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.net.URLEncoder;

@Controller
@RequestMapping("/wechat")
public class WechatLoginController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxMpService wxMpService;

    @GetMapping("/authorize")
    public String authorize(String returnUrl){
        String url="http://kyj.com.tunnel.qydev.com/wechat/userInfo";
        @SuppressWarnings("deprecation")
        String result = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO , URLEncoder.encode(returnUrl));
        logger.info("【微信网页授权】 获取code，request："+result);
        return "redirect:"+result;
    }

    @GetMapping("/userInfo")
    public String userInfo(String code,String state){
        WxMpOAuth2AccessToken accessToken = null;
        WxMpUser wxMpUser=null;
        try {
            accessToken = wxMpService.oauth2getAccessToken(code);
            wxMpUser = wxMpService.oauth2getUserInfo(accessToken, "");
            logger.info("【微信网页授权成功】用户信息： " + wxMpUser);
        } catch (WxErrorException e) {
            // TODO Auto-generated catch block
            logger.error("【微信网页授权失败】 "+e+"错误："+e.getMessage());
            e.printStackTrace();
        }
        String openId = accessToken.getOpenId();
        return  "redirect:http://kyj.com.tunnel.qydev.com/app/customer/tomyui";
    }




}
